package com.hjs.homework.table;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class FlinkTableDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        EnvironmentSettings setting = EnvironmentSettings.newInstance()
                .useBlinkPlanner()
                .inStreamingMode()
                .build();
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env, setting);
        env.setParallelism(1);
        DataStreamSource<Tuple2<String, Integer>> data = env.addSource(new SourceFunction<Tuple2<String, Integer>>() {
            @Override
            public void run(SourceContext<Tuple2<String, Integer>> sourceContext) throws Exception {
                int i = 1;
                while (true) {
                    sourceContext.collect(new Tuple2<String, Integer>("index" + i, i));
                    i++;
                    Thread.sleep(1000);
                }
            }

            @Override
            public void cancel() {

            }
        });

        tEnv.createTemporaryView("indexTable",data,$("name"),$("age"));
        Table sqlQuery = tEnv.sqlQuery("select * from indexTable where mod(age,2) = 0");
        DataStream<Tuple2<Boolean, Row>> dataStream = tEnv.toRetractStream(sqlQuery, Row.class);
        dataStream.print();

        /*Table table = tEnv.fromDataStream(data, $("name"), $("age"));
        Table name = table.select($("name"), $("age")).filter($("age").mod(2).isEqual(0));
        DataStream<Tuple2<Boolean, Row>> toRetractStream = tEnv.toRetractStream(name, Row.class);
        toRetractStream.print();*/

        env.execute();
    }
}
